package com.study.zookeeperAPI;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class GetChildrenSync implements Watcher {

    private static CountDownLatch latch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper = null;

    public static void main(String[] args) {
        String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
        String path = "/zk-book";
        try{
            zooKeeper = new ZooKeeper(connectStr, 5000, new GetChildrenSync());
            latch.await();
            zooKeeper.create(path,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zooKeeper.create(path+"/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);

            List<String> childrenList = zooKeeper.getChildren(path, true);
            System.out.println("first childrentList=====" + childrenList);

            zooKeeper.create(path+"/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            Thread.sleep(Integer.MAX_VALUE);

        }catch (IOException e){

        }catch (InterruptedException e){

        }catch (KeeperException e){

        }


    }

    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){
            if(Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()){
                latch.countDown();
            }else if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged){
                try{
                    System.out.println("ReGet Child: "+ zooKeeper.getChildren(watchedEvent.getPath(), true));
                }catch (Exception e){
                    System.out.println("Exception-----" + e.getMessage());
                }
            }
        }
    }
}
